<?

$_GET['url-rewrited'] = 'y';

require_once(dirname(__FILE__) . '/libs/bf/bf.php');
require_once(dirname(__FILE__) . '/rewrite.config.php');

$applications = @scandir('applications');
if (!is_array($applications))
	$applications = array();
foreach ($applications as $app) {
	if (!preg_match('/^\./', $app)) {
		require_once(dirname(__FILE__) . '/applications/' . $app . '/config/application.php');
	}
}

$log_rewrite = new bf_log($rewrite_config['log']);

$result = bf::$url->rewrite(@$_SERVER['REQUEST_URI']);
if (is_array($result)) {
	foreach ($result['params'] as $name => $value)
		bf::$request->set($name, $value);
	$file = $result['file'];
	$file = (preg_match('/\.\./', $file) ? 'index.php' : $file);
	$file = (preg_match('/^\//', $file) ? ".$file" : $file);
	if ($file != basename(__FILE__)) {
		$log_rewrite->append('' . date('Y-m-d H:i:s') . ' ' . bf::$inet->client_address() . " {$_SERVER['REQUEST_URI']} -> {$result['url']} -> $file\n");
		$info = pathinfo($file);
		include($file);
		if ($info && ($info = (object) $info)) {
			$controller_class = 'controller_' . preg_replace('/[\.\-]+/', '_', $info->filename);
			if (class_exists($controller_class)) {
				$exec_controller = create_function(
					'$config',
					'return new ' . $controller_class . '($config);'
				);
				$controller = $exec_controller(
					(isset(bf::$application->config['controller'][$controller_class])
					? bf::$application->config['controller'][$controller_class]
					: null)
				);
				if (in_array('execute', get_class_methods($controller))) {
					$controller->execute();
				}
			}
		}
	}
} else {
	$log_rewrite->append('' . date('Y-m-d H:i:s') . ' ' . bf::$inet->client_address() . " {$_SERVER['REQUEST_URI']} -> NOT rewrited\n");
	include($rewrite_config['default']);
}

?>